/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.editor.structure;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.data.CMSSection;
import org.gidoo.cms.data.Folder;
import org.gidoo.cms.data.Page;
import org.gidoo.cms.data.Resource;
import org.gidoo.cms.dbconnection.DatabaseConnectionException;
import org.gidoo.cms.dbconnection.Persistance;
import org.gidoo.cms.editor.EditorPage;
import org.gidoo.cms.helper.Tools;

/**
 *
 * @author thomas
 */
public class StructurePanel extends Panel
{

  private Form mainForm;
  private TextField txtNewFolderName;
  private AjaxButton btAdd;
  private AjaxButton btDelete;
  private AjaxButton btUp;
  private AjaxButton btDown;
  private AjaxButton btCut;
  private AjaxButton btPaste;
  private TextField txtRename;
  private AjaxButton btRename;
  
  private Folder theFolder;

  private EditorPage parentPage;
    
  public StructurePanel(String id, Folder folder, EditorPage parent)
  {
    super(id);
    
    try
    {

      this.parentPage = parent;      
      theFolder = folder;

      mainForm = new Form("mainForm");

      btUp = new AjaxButton("btUp") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          folderUp();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btUp.setModel( new Model(getString("up")));
      mainForm.add(btUp);
      
      btDown = new AjaxButton("btDown"){

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          folderDown();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btDown.setModel(new Model(getString("down")));
      mainForm.add(btDown);
      
      txtNewFolderName = new TextField("txtNewFolderName", new Model(""));
      mainForm.add(txtNewFolderName);

      btAdd = new AjaxButton("btAdd")
      {
        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          addFolder();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
        }
        
      };
      
      btAdd.setModel(new Model(getString("add")));
      mainForm.add(btAdd);

      btDelete = new AjaxButton("btDelete") {


        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          deleteFolder();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
        }
      };
      btDelete.setModel(new Model(getString("delete")));
      mainForm.add(btDelete);

      btCut = new AjaxButton("btCut") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          cut();
          target.addComponent(parentPage.getFeedbackPanel());
        }
      };
      btCut.setModel(new Model(getString("cut")));
      
      btCut.setEnabled(theFolder != null && theFolder.getParent() != null);
      
      mainForm.add(btCut);
      
      btPaste = new AjaxButton("btPaste") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          paste();
          
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
        }
      };
      btPaste.setModel(new Model(getString("paste")));
      
      btPaste.setEnabled(
        theFolder != null &&
        parentPage.getLastCutID() >= 0 
        && parentPage.getLastCutID() != theFolder.getId());
      
      mainForm.add(btPaste);
      
      txtRename = new TextField("txtRename", new Model(""));
      txtRename.setEnabled(theFolder != null && theFolder.getParent() != null);
      mainForm.add(txtRename);
      
      btRename = new AjaxButton("btRename") {

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form form)
        {
          rename();
          target.addComponent(parentPage.getFeedbackPanel());
          target.addComponent(parentPage.getTreeNav());
          target.addComponent(parentPage.getPanelTabs());
          
        }
      };      
      btRename.setModel(new Model(getString("rename")));
      btRename.setEnabled(theFolder != null && theFolder.getParent() != null);
      mainForm.add(btRename);
      
      add(mainForm);

      if(theFolder == null)
      {
        mainForm.setVisible(false);
      }
      else if(theFolder.getSection().getRootFolder().equals(theFolder))
      {
        btDelete.setVisible(false);

      }
    }
    catch(DatabaseConnectionException ex)
    {
      error("dberror");
    }

  }

  private void rename()
  {
    String newName = txtRename.getModelObjectAsString();
    Folder parentFolder = theFolder.getParent();
    
    if(newName == null || "".equals(newName))
    {
      error(getString("namewasnull"));
    }
    else if(parentFolder == null)
    {
      error(getString("sectionnotallowed"));
    }
    else if(newName.contains("/"))
    {
      error(getString("noslashallowed"));
    }
    else
    {
      try
      {
        // check if already existant
        List<Folder> children =  ((GidooCMS) getApplication()).getDb().getChildrenOfFolder(parentFolder);
        for(Folder c : children)
        {
          if(c.getName().equals(newName))
          {
            error(getString("alreadyexists"));
            return;
          }
        }
        
        theFolder.setName(newName);
        theFolder = (Folder) ((GidooCMS) getApplication()).getDb().merge(theFolder); 
      }
      catch (DatabaseConnectionException ex)
      {
        Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("dberror"));
      }
            
    }
    parentPage.updateDataAndView(theFolder);
  }
  
  private void cut()
  {
    parentPage.setLastCutID(theFolder.getId());
    info(getString("wascutted"));    
  }
  
  private void paste()
  {
    if(parentPage.getLastCutID() >= 0)
    {
      try
      {
        Folder folderToMove = ((GidooCMS) getApplication()).getDb().getFolderById(parentPage.getLastCutID());
        Folder oldParent = folderToMove.getParent();
        
        parentPage.setLastCutID(-1);
        
        if(folderToMove.getParent() == null )
        {
          error(getString("sectionnotallowed"));
          return;
        }
        if(folderToMove.equals(theFolder))
        {
          return;
        }
        
        List<Folder> childrenOfNewFolder = ((GidooCMS) getApplication()).getDb().getChildrenOfFolder(theFolder);
        
        folderToMove.setParent(theFolder);
        CMSSection newSection = theFolder.getSection();
        folderToMove.setSection(newSection);
        folderToMove.setPosition(childrenOfNewFolder.size());
        Folder[] subFolders = Tools.getAllSubfolders(folderToMove, (GidooCMS) getApplication());
        for(Folder f : subFolders)
        {
          f.setSection(newSection);
        }
        
        folderToMove = (Folder) ((GidooCMS) getApplication()).getDb().merge(folderToMove);
        ((GidooCMS) getApplication()).getDb().merge(subFolders);
        
        List<Folder> childrenOfOldParent = ((GidooCMS) getApplication()).getDb().getChildrenOfFolder(oldParent);
        
        childrenOfOldParent = ((GidooCMS) getApplication()).getDb().mergeListOfFolders(childrenOfOldParent);
        
        parentPage.updateDataAndView(folderToMove);
        
        info(getString("moved"));
      }
      catch (DatabaseConnectionException ex)
      {
        Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("dberror"));
      }
      
    }
  }
  
  private void addFolder()
  {
    if(theFolder == null)
    {
      warn(getString("null"));
      return;
    }

    String name = txtNewFolderName.getModelObjectAsString();
    if(name != null && !"".equals(name))
    {
      try
      {

        // check for unallowed characters
        if(name.contains("/"))
        {
          error(getString("noslashallowed"));
          return;
        }
        
        // check if already existant
        List<Folder> children = ((GidooCMS) getApplication()).getDb().getChildrenOfFolder(theFolder);
        for(Folder c : children)
        {
          if(c.getName().equals(name))
          {
            error(getString("alreadyexists"));
            return;
          }
        }
      
        
        // construct a new Folder
        Folder f = new Folder();
        f.setHistory(new LinkedList<Page>());
        f.setName(name);
        f.setPageWaitingForPublisher(null);
        f.setPublishedPage(null);
        f.setSection(theFolder.getSection());
        f.setParent(theFolder);
        f.setPosition(children.size());
        f.setResources(new LinkedList<Resource>());
        
        ((GidooCMS) getApplication()).getDb().persist(f);

      }
      catch(DatabaseConnectionException ex)
      {
        Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("dberror"));
      }
    }
    else
    {
      error(getString("namewasnull"));
    }
    
    parentPage.updateDataAndView();
    
  }

  private void deleteFolder()
  {
    Folder parent = theFolder.getParent();
      
    try
    {
      Page page;
      
      if(theFolder == null)
      {
        warn(getString("null"));
      }
      else if(((GidooCMS) getApplication()).getDb().getChildrenOfFolder(theFolder).size() > 0)
      {
        error(getString("nosubpagesallowed"));
      }
      else
      {
        if((page = theFolder.getPublishedPage()) == null 
          || ("".equals(page.getTitle()) && "".equals(page.getContentAsXML())))
        {
          // everything is prepared for deleting the folder
          ((GidooCMS) getApplication()).getDb().remove(theFolder);
          
          // update the positions of the siblings
          ((GidooCMS) getApplication()).getDb().mergeListOfFolders(((GidooCMS) getApplication()).getDb().getChildrenOfFolder(parent));
          
        }
        else
        {
          error(getString("pagemustbeemptybeforedelete"));
        }
      }
    }
    catch(DatabaseConnectionException ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("dberror"));
    }
    
    parentPage.updateDataAndView(parent);
    
  }
  
  private void folderUp()
  {
    if(theFolder == null)
      return;
    
    try
    {
      Folder parent = theFolder.getParent();
      if(parent != null)
      {
        List<Folder> siblings = new ArrayList<Folder>(((GidooCMS) getApplication()).getDb().getChildrenOfFolder(parent));
        int oldPosition = theFolder.getPosition();
        
        if(oldPosition > 0 && oldPosition < siblings.size())
        {
          Folder tmp = siblings.get(oldPosition-1);
          siblings.set(oldPosition-1, theFolder);
          siblings.set(oldPosition, tmp);
          siblings = ((GidooCMS) getApplication()).getDb().mergeListOfFolders(siblings);
          theFolder = siblings.get(oldPosition-1);
        }
      }
    }
    catch (Exception ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("dberror"));

    }
    
    parentPage.updateDataAndView();
  }
  
  private void folderDown()
  {
    if(theFolder == null)
      return;
        
    try
    {
      Folder parent = theFolder.getParent();
      if(parent != null)
      {
        List<Folder> siblings = new ArrayList<Folder>(((GidooCMS) getApplication()).getDb().getChildrenOfFolder(parent));
        int oldPosition = theFolder.getPosition();
        
        if(oldPosition >= 0 && oldPosition < siblings.size()-1)
        {
          Folder tmp = siblings.get(oldPosition+1);
          siblings.set(oldPosition+1, theFolder);
          siblings.set(oldPosition, tmp);
          siblings = ((GidooCMS) getApplication()).getDb().mergeListOfFolders(siblings);
          theFolder = siblings.get(oldPosition+1);
        }
      }
    }
    catch (Exception ex)
    {
      Logger.getLogger(StructurePanel.class.getName()).log(Level.SEVERE, null, ex);
      error(getString("dberror"));

    }
        
    parentPage.updateDataAndView();
    
  }

}
